package com.yfree.global

import com.google.gson.Gson
import com.google.gson.internal.LinkedTreeMap
import com.yfree.config.YConfig
import com.yfree.model.YBaseModel
import com.yfree.model.YModel
import com.yfree.model.YRootModel
import com.yfree.utils.YAESCrypt
import org.slf4j.LoggerFactory
import org.springframework.web.bind.annotation.RestController

@RestController
class YController {
    var gson = Gson()
    var yLog = LoggerFactory.getLogger("YFreeLog")

    fun <T> params(jkparam: String?, classOfT: Class<T>): T {
        val param = jkparam ?: "{}"
        val json = if (YConfig.Encrypt.enable) YAESCrypt.decrypt(param, YConfig.Encrypt.key) else param
        return gson.fromJson(json, classOfT)
    }

    fun json(code: Int = YConfig.Response.successCode, result: List<YBaseModel> = arrayListOf(), message: String = YConfig.Response.successMsg): String {
        val json = gson.toJson(YModel(
                YRootModel("$code", message, result)
        ))
        return if (YConfig.Encrypt.enable) YAESCrypt.encrypt(json, YConfig.Encrypt.key) else json
    }

    fun <T : YBaseModel> fromJson(json: String?, clazz: Class<T>): YModel<T> {
        val yModel = gson.fromJson<YModel<T>>(json, YModel::class.java)
        val ts = arrayListOf<T>()
        val map = gson.fromJson(json, Map::class.java)
        val result = (map["root"] as Map<String, Any>)["result"] as List<LinkedTreeMap<String, Any>>
        result.forEach {
            ts.add(gson.fromJson(gson.toJson(it), clazz))
        }
        yModel.root.result = ts
        return yModel
    }

    fun yfree_defaultFallback(): String {
        return json(code = YConfig.Response.fallBackCode, message = YConfig.defaultFallback)
    }
}
